import json
from sqlalchemy import select
from forward.api.admin.schemas.operator import (
    OperatorConfigInSchema,
    OperatorListInSchema,
)
from forward.api.admin.schemas.system import (
    SystemAuthAdminOutSchema,
    SystemAuthDeptOutSchema,
    SystemAuthPostOutSchema,
    SystemAuthRoleSchema,
)
from forward.exceptions.base import AppException
from forward.extend.pydantic.result_api import ResultAPI
from forward.dependencies.database import db
from forward.http_base import HttpResp
from forward.model.tables.system import (
    SystemAuthAdminModel,
    SystemAuthDeptModel,
    SystemAuthPostModel,
    SystemAuthRoleModel,
)
from forward.utils.config import ConfigUtil
from forward.utils.tools import ToolsUtil
from forward.utils.urls import UrlUtil


class OperatorService:
    @classmethod
    def instance(cls):
        return OperatorService()

    async def lists(self, list_in: OperatorListInSchema):
        config = await ConfigUtil.get_map("admin_pc", "operator")
        print("dept_id", config, type(config))
        if not config:
            raise AppException(exc=HttpResp.FAILED, msg="页面未配置")
        dept_id = config.get("dept_id", 0)
        if not dept_id:
            raise AppException(exc=HttpResp.FAILED, msg="未配置部门ID")
        where = []
        where.append(SystemAuthAdminModel.is_delete == 0)
        where.append(SystemAuthAdminModel.dept_ids.like(f"%{str(dept_id)}%"))
        if list_in.name:
            where.append(SystemAuthAdminModel.nickname.like(f"%{list_in.name}%"))

        statement = (
            select(
                SystemAuthAdminModel,
                SystemAuthAdminModel.role_ids.label("role"),
                SystemAuthAdminModel.dept_ids.label("dept"),
                SystemAuthAdminModel.post_ids.label("post"),
            )
            .where(*where)
            .order_by(SystemAuthAdminModel.id.desc())
        )
        records = await db.fetch_all(statement)
        admins = [
            SystemAuthAdminOutSchema.model_validate(record, from_attributes=True)
            for record in records
        ]
        # 处理返回结果
        for obj in admins:
            obj.avatar = await UrlUtil.to_absolute_url(obj.avatar)
            if obj.id == 1:
                obj.role = "系统管理员"
            else:
                # 角色
                role_ids = [int(i) for i in (obj.role or "").split(",") if i.isdigit()]
                roles = await db.fetch_all(
                    select(SystemAuthRoleModel).where(
                        SystemAuthRoleModel.id.in_(role_ids)
                    )
                )
                roles = [
                    SystemAuthRoleSchema.model_validate(role, from_attributes=True)
                    for role in roles
                ]
                obj.role = "/".join([i.name for i in roles])
            if not obj.dept:
                obj.dept = ""
            else:
                # 部门
                dept_ids = [int(i) for i in obj.dept.split(",") if i.isdigit()]
                depts_record = await db.fetch_all(
                    select(SystemAuthDeptModel).where(
                        SystemAuthDeptModel.id.in_(dept_ids),
                        SystemAuthDeptModel.is_delete == 0,
                    )
                )
                depts = [
                    SystemAuthDeptOutSchema.model_validate(
                        dept_record, from_attributes=True
                    )
                    for dept_record in depts_record
                ]
                obj.dept = "/".join([i.name for i in depts])
            if not obj.post:
                obj.post = ""
            else:
                # 岗位
                post_ids = [int(i) for i in obj.post.split(",") if i.isdigit()]
                post_record = await db.fetch_all(
                    select(SystemAuthPostModel).where(
                        SystemAuthPostModel.id.in_(post_ids),
                        SystemAuthPostModel.is_delete == 0,
                    )
                )
                posts = [
                    SystemAuthPostOutSchema.model_validate(
                        post_record, from_attributes=True
                    )
                    for post_record in post_record
                ]
                obj.post = "/".join([i.name for i in posts])

        return ResultAPI(
            data={
                "count": len(admins),
                "lists": admins,
                "pageNo": list_in.page_no,
                "pageSize": list_in.page_size,
            }
        )

    async def set_config(self, config_in: OperatorConfigInSchema):
        await ConfigUtil.set("admin_pc", "operator", config_in.model_dump_json())
